# coding: utf-8

from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel
from PyQt5.QtCore import Qt, QUrl
from PyQt5.QtGui import  QPixmap, QFont, QImage, QPainter, QPainterPath
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetworkRequest

from qfluentwidgets import CardWidget
# from resource import *


class CommentCard(CardWidget):
    def __init__(
        self,
        parent=None,
        avatar: str = "",
        nickName: str = "",
        comment: str = "",
        time: str = "",
    ):
        super().__init__(parent)
        self.avatarUrl = avatar
        self.nickName = nickName
        self.comment = comment
        self.time = time

        self.userAvatarLabel = QLabel(self)
        self.userNickNameLabel = QLabel(self)
        self.commentLabel = QLabel(self)
        self.timeLabel = QLabel(self)

        self.__initWidget()

    def __initWidget(self):
        self.userNickNameLabel.setText(self.nickName)
        self.userNickNameLabel.setFont(self._setFont("HarmonyOS Sans SC", 10))
        
        self.userAvatarLabel.setFixedSize(35,35)
        self.userAvatarLabel.setScaledContents(True)

        self.timeLabel.setText(self.time)
        self.timeLabel.setFont(self._setFont("HarmonyOS Sans SC", 8))
        self.timeLabel.setStyleSheet("color: #B6B6B6")

        self.commentLabel.setText(self.comment)
        self.commentLabel.setWordWrap(True)
        self.commentLabel.setFont(self._setFont("HarmonyOS Sans SC", 12))

        self.__initLayout()
        self._loadImage(self.avatarUrl)

    def __initLayout(self):
        self.layouts = QVBoxLayout(self)
        self.userInfoLayout = QHBoxLayout()
        self.timeLayout = QVBoxLayout()
        self.layouts.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.timeLayout.setSpacing(0)
        self.timeLayout.addWidget(self.userNickNameLabel, 0, Qt.AlignmentFlag.AlignTop)
        self.timeLayout.addWidget(self.timeLabel, 0, Qt.AlignmentFlag.AlignTop)

        self.userInfoLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.userInfoLayout.addWidget(
            self.userAvatarLabel, 0, Qt.AlignmentFlag.AlignLeft
        )
        self.userInfoLayout.addLayout(self.timeLayout)

        self.layouts.addLayout(self.userInfoLayout)
        self.layouts.addWidget(self.commentLabel, 0, Qt.AlignmentFlag.AlignTop)

    def _setFont(self, fontFamily, fontSize):
        font = QFont()
        font.setFamily(fontFamily)
        font.setPointSize(fontSize)
        return font

    def _setRoundedImage(self, label, pixmap, radius):
        pixmap = pixmap.scaled(
            label.size(), Qt.AspectRatioMode.KeepAspectRatioByExpanding
        )

        rounded_pixmap = QPixmap(pixmap.size())
        rounded_pixmap.fill(Qt.transparent)

        painter = QPainter(rounded_pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        path = QPainterPath()
        path.addRoundedRect(0, 0, pixmap.width(), pixmap.height(), radius, radius)
        painter.setClipPath(path)
        painter.drawPixmap(0, 0, pixmap)
        painter.end()

        label.setPixmap(rounded_pixmap)
        label.setScaledContents(True)

    # 网络线程加载图片
    # TODO: 优化流程
    def _loadImage(self, url):
        # 创建QNetworkAccessManager实例
        self.manager = QNetworkAccessManager(self)
        # 连接信号
        self.manager.finished.connect(self._imageLoaded)

        # 创建QNetworkRequest
        request = QNetworkRequest(QUrl(url))

        # 发送GET请求
        self.manager.get(request)

    def _imageLoaded(self, reply):
        # 检查请求是否成功
        if reply.error() == QNetworkReply.NoError:
            # 将网络回复转换为QImage
            image = QImage()
            image.loadFromData(reply.readAll())
            # 将QImage转换为QPixmap并设置到QLabel
            self._setRoundedImage(self.userAvatarLabel, QPixmap.fromImage(image), 20)
        else:
            self._setRoundedImage(
                self.userAvatarLabel, QPixmap(":app/images/defaultAvatar.jpg"), 20
            )


# class Demo(QWidget):
#     def __init__(self):
#         super().__init__()
#         card = CommentCard(
#             self,
#             "http://api.xzwmc.com:8000/up/upload/uploads/65c4e8a1c451c_stemp.png",
#             "威廉我",
#             "这是一条测试评论这是一条测试评论这是一条测试评论这是一条测试评论",
#             "2024/5/5 24:00"
#         )


# if __name__ == "__main__":
#     QApplication.setHighDpiScaleFactorRoundingPolicy(
#         Qt.HighDpiScaleFactorRoundingPolicy.PassThrough
#     )
#     QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
#     QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
#     app = QApplication(sys.argv)
#     fontDb = QFontDatabase()
#     fontNames = ["harmonyos"]
#     for fontname in fontNames:
#         fontID = fontDb.addApplicationFont(
#             f":app/fonts/{fontname}.ttf"
#         )

#     fontFamilies = fontDb.applicationFontFamilies(fontID)
#     print(fontFamilies)
#     w = Demo()
#     w.show()
#     app.exec()
